//
//  UploadOssModule.m
//  WeexEros
//
//  Created by 侍晓明 on 2019/2/28.
//  Copyright © 2019年 benmu. All rights reserved.
//

#import "UploadOssModule.h"
#import <WeexPluginLoader/WeexPluginLoader.h>
#import <AliyunOSSiOS/OSSService.h>


// 第一个参数为暴露给 js 端 Module 的名字，
// 第二个参数为你 Module 的类名
WX_PlUGIN_EXPORT_MODULE(uploadOss, UploadOssModule)

@implementation UploadOssModule

@synthesize weexInstance;

// 将方法暴露出去
//WX_EXPORT_METHOD(@selector(test:))
WX_EXPORT_METHOD(@selector(upload:objName:callback:))


static NSString *const AccessKey = @"LTAIzcxMECP4NFkX";
static NSString *const SecretKey = @"kp4w2oVlhzKhqhpfxRcwwQAEGD89Qs";
static NSString *const BucketName = @"jshyzn";
static NSString *const AliYunHost = @"http://oss-cn-hangzhou.aliyuncs.com";
static NSString *kTempFolder = @"";

// 实现 Module 方法
-  (void)upload:(NSString *)path objName:(NSString *)objName callback:(WXModuleCallback)callback
{
    NSData *image = [NSData dataWithContentsOfFile:path];
    UIImage *img =[UIImage imageWithData:image];
    
    kTempFolder = objName;
    [self syncUploadImage:img complete:^(NSArray<NSString *> *names, UploadImageState state) {
        NSDictionary *data = nil;
        if(state == UploadImageSuccess){
            NSString *url = [@"https://jshyzn.oss-cn-hangzhou.aliyuncs.com/" stringByAppendingString:[names objectAtIndex:0]];
            data = @{@"result": @"success",@"url": url};
            callback(data);
        }else{
            data = @{@"result": @"false"};
            callback(data);
        }
        
    }];
   
    
}



- (void)asyncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    [self uploadImages:@[image] isAsync:YES complete:complete];
}

- (void)syncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    [self uploadImages:@[image] isAsync:NO complete:complete];
}

- (void)asyncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [self uploadImages:images isAsync:YES complete:complete];
}

- (void)syncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [self uploadImages:images isAsync:NO complete:complete];
}

- (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey                                                                                                            secretKey:SecretKey];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = images.count;
    
    NSMutableArray *callBackNames = [NSMutableArray array];
    int i = 0;
    for (UIImage *image in images) {
        if (image) {
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                //任务执行
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                put.bucketName = BucketName;
                
                //文件路径及名称拼接
//                NSString *imageName = [kTempFolder stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:@".jpg"]];
                NSString *imageName = kTempFolder;
                put.objectKey = imageName;
                put.contentType = @"image/png";
                //添加到数组回传
                [callBackNames addObject:imageName];
                
                //上传date
                NSData *data = UIImageJPEGRepresentation(image, 0.3);
                put.uploadingData = data;
                // 阻塞直到上传完成
                OSSTask * putTask = [client putObject:put];
                [putTask waitUntilFinished];
                if (!putTask.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , putTask.error);
                    complete([NSArray arrayWithArray:callBackNames],UploadImageFailed);
                }
                if (isAsync) {
                    if (image == images.lastObject) {
                        NSLog(@"upload object finished!");
                        if (complete) {
                            complete([NSArray arrayWithArray:callBackNames] ,UploadImageSuccess);
                        }
                    }
                }
            }];
            if (queue.operations.count != 0) {
                [operation addDependency:queue.operations.lastObject];
            }
            [queue addOperation:operation];
        }
        i++;
    }
    if (!isAsync) {
        [queue waitUntilAllOperationsAreFinished];
        if (complete) {
            if (complete) {
                complete([NSArray arrayWithArray:callBackNames], UploadImageSuccess);
            }
        }
    }
}
@end

